<?php
namespace api\common\controllers;


use yii\base\Event;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\ContentNegotiator;
use yii\filters\RateLimiter;
use yii\filters\VerbFilter;
use yii\rest\ActiveController;
use yii\web\Response;

/**
 * 基类controller
 * API规则
 * 1、API数据成功与否  需要判断status   status->1 成功  status->0 失败
 * 2、根据code做对应业务操作   需要先判断  status->0  然后判断code
 * 3、数据体是data  需要先判断 status->1  然后取data
 * 4、msg只做提供给开发者查看错误信息，不做Toast信息提示（后期如果有这个需求，后面再加字段）
 * Class BaseController
 * @package api\common\controllers
 */
class BaseController extends ActiveController{

//    public $enableCsrfValidation = true;

    public $modelClass = "";

    public static $CODE = 200;

    public static $STATUS = 1;

    public static $STATUSTEXT = 'OK';

    public static $FIELDS_KEY = 'default';

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        /** @var \yii\base\Event $event */
        \Yii::$app->response->on(Response::EVENT_BEFORE_SEND,function (Event $event){
            /** @var \yii\web\Response $response */
            $response = $event->sender;
            if(!is_string($response->data)){
                if(static::$CODE==200){
                    static::$STATUS = 1;
                }else{
                    static::$STATUS = 0;
                    static::$STATUSTEXT = $response->statusText;
                }

                if($response->isSuccessful){
                    $response->data = [
                        'code' => static::$CODE,
                        'status' => static::$STATUS,
                        'msg' => static::$STATUSTEXT,
                        'data' => static::$CODE==200?$response->data:null
                    ];
                }else{
                    $response->data = [
                        'code' => $response->statusCode,
                        'status' => 0,
                        'msg' => @$response->data[0]['message']?@$response->data[0]['message']:@$response->data['message'],
                        'data' => null,
                    ];
                }
            }
        });
    }

    /**
     * 加载默认值
     * @param bool $skipIfSet
     * @param $default
     * @param $model
     * @return mixed
     */
    public function loadDefaultValue($skipIfSet = true,$default,$model){
        if($default){
            foreach ($default as $attribute => $value){
                if($model->{$attribute} !== null and $skipIfSet == true){
                    continue;
                }
                $model->{$attribute} = $value;
            }
        }
        return $model;
    }

    /**
     * 服务器异常调用
     * @return array
     */
    public function actionError(){
        return [
            'code' => 500,
            'status' => 0,
            'msg' => '服务器错误',
            'data' => null,
        ];
    }

    public function behaviors()
    {
//        $behaviors = parent::behaviors(); // TODO: Change the autogenerated stub
        $behaviors = [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ],
            ],
            'verbFilter' => [
                'class' => VerbFilter::className(),
                'actions' => $this->verbs(),
            ],
            'authenticator' => [
                'class' => HttpBearerAuth::className(),
                'header' => 'token',
                'pattern' => '/^token\s+(.*?)$/'
            ],
            'rateLimiter' => [
                'class' => RateLimiter::className(),
            ],
        ];
        //$behaviors['authenticator']['optional'] = ['login']; 说明登录不需要token 验证
        $behaviors['authenticator']['optional'] = ['register'];
        return $behaviors;
    }
}
